package com.luoran.car.controller;

import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.luoran.car.domain.SysCarCoupon;
import com.luoran.car.service.SysCarCouponService;
import com.luoran.car.util.AjaxResult;
import com.luoran.common.core.domain.R;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;

@RestController
@RequestMapping("/coupon")
public class CouponController {

    @Autowired
    private SysCarCouponService sysCarCouponService;


    /**
     * 分页查询优惠券列表
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/getCouponList")
    public AjaxResult getCouponList(Integer current, Integer size, SysCarCoupon coupon){
        PageHelper.startPage(current,size);
        List<SysCarCoupon> list = sysCarCouponService.getCouponList(coupon);
        PageInfo<SysCarCoupon> pageInfo = new PageInfo<>(list);
        return AjaxResult.success(pageInfo);
    }


    /**
     * 新增优惠券
     * @param coupon
     * @return
     */
    @PostMapping("/addConPon")
    public AjaxResult addConPon(@RequestBody SysCarCoupon coupon){
        boolean b = sysCarCouponService.addConPon(coupon);
        return AjaxResult.success(b);
    }

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.url}")
    private String url;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @PostMapping("/uploader")
    public R upload(MultipartFile file){
        String fileName = file.getOriginalFilename();
        String name = fileName.substring(fileName.indexOf("."));
        name = IdUtil.getSnowflakeNextIdStr()+name;
        System.out.println(name+"----------------");
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(name)
                    .stream(file.getInputStream(),file.getSize(),-1)
                    .contentType(file.getContentType())
                    .build());
        }catch (Exception e){
            e.printStackTrace();
        }

        String pic = url+"/"+bucketName+"/"+name;
        System.out.println(pic+"----------------");

        return R.ok(pic);
    }


    @PostMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable("id") Integer id){
       boolean b = sysCarCouponService.deleteCouponById(id);
       return AjaxResult.success(b);
    }

}
